﻿
using Basic.Api.Web.Extensions;
using Basic.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Basic.Common.Web.Extensions
{
    public class DatetimeJsonConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String)
            {
                if (DateTime.TryParse(reader.GetString(), out DateTime date))
                    return date;
            }
            return reader.GetDateTime();
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }

    public static class StartupDefaultExtend
    {
        public static void DefaultService(this IServiceCollection services)
        {
            services.AddControllers(cfg => {
                cfg.Filters.Add<ActionFilter>();
                //cfg.Filters.Add<ExceptionFilter>();
            }).AddJsonOptions(configure => {
                configure.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
            });
            
            services.AddSwaggerGenService();
            //services.AddDbContext<Basic.Entites.EFDbContext>();
            services.AddScoped(typeof(MinioFileService));
            //添加cors 服务 配置跨域处理   
            services.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
                    .AllowAnyHeader()
                    //.AllowCredentials()//指定处理cookie
                    .AllowAnyOrigin() //允许任何来源的主机访问
                    .WithExposedHeaders(new string[] { "X-Pagination" });

                });
            });
        }

        public static void DefaultConfigure(this IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.SwaggerGenConfigure();
            }
            app.UseAuthentication();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseCors("any");
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }



}
